package com.sskj.qiangjin.presenter;

import android.util.Log;

import com.google.gson.Gson;
import com.lzy.okgo.model.Response;
import com.sskj.common.base.HttpData;
import com.sskj.common.http.WebSocketObserver;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.util.DisposUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.lib.Constans;
import com.sskj.lib.bean.UserBean;
import com.sskj.lib.http.JsonCallBack;
import com.sskj.qiangjin.bean.NewNoticeBean;
import com.sskj.qiangjin.bean.SocketSendBean;
import com.sskj.qiangjin.bean.StockBloomBean;
import com.sskj.qiangjin.bean.UpdataBean;
import com.sskj.qiangjin.http.HttpConfig;
import com.sskj.qiangjin.ui.activity.MainActivity;

import org.reactivestreams.Publisher;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;


public class MainActivityPresenter extends BasePresenter<MainActivity> {
    private WebSocketObserver stockSocket;
    private Disposable stockDisposable;
    private Disposable timeDisposed;
    int currentMillers = 0;

    public void initWebSocket() {
        if (stockSocket == null) {
            RxBus.getDefault().register(this);
            stockSocket = httpService.pushBloomType(Constans.DEFAULT_BIBI_COIN);
            stockDisposable = stockSocket
                    .toFlowable(BackpressureStrategy.DROP)
                    .subscribeOn(Schedulers.io())
                    .flatMap((Function<String, Publisher<String>>) text -> {
                        ArrayList<String> strings = new ArrayList<>();
                        strings.add(text);
                        return Flowable.fromIterable(strings);
                    })
                    .map(s -> new Gson().fromJson(s, StockBloomBean.class))
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(data -> {
                        RxBus.getDefault().post(data);
                        currentMillers = 0;
                        //5秒后没有收到下一次推送，判定为卡住，断开重连
                        if (timeDisposed != null) {
                            DisposUtil.close(timeDisposed);
                        }
                        timeDisposed = Observable.interval(0, 1, TimeUnit.SECONDS)
                                .subscribeOn(Schedulers.newThread())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(aLong -> {
                                    currentMillers++;
                                    Log.i("out", currentMillers + "");
                                    if (currentMillers == 2) {
//                                stockSocket.send(new Gson().toJson(new SocketSendBean(Constans.DEFAULT_BIBI_COIN)));
                                        Log.i("out", "重新发送");
                                        closeWebSocket();
                                        initWebSocket();
                                    }
                                });
                    });
        } else {
            stockSocket.send(new Gson().toJson(new SocketSendBean(Constans.DEFAULT_BIBI_COIN)));
        }
    }


    public void closeWebSocket() {
        stockSocket = null;
        DisposUtil.close(stockDisposable);
    }


    public void closeTimeSocket() {
        if (timeDisposed != null) {
            DisposUtil.close(timeDisposed);
        }
    }


    /**
     * 是否有新公告
     */
    public void isHaveNoticeList() {
        httpService.isHaveNoticeList(1, 10)
                .tag(this)
                .execute(new JsonCallBack<HttpData<NewNoticeBean>>(this) {
                    @Override
                    public void onSuccess(Response<HttpData<NewNoticeBean>> response) {
                        HttpData httpData = response.body();
//                        ToastUtil.showShort(httpData.msg);
                        if (httpData.getStatus() == HttpConfig.OK) {
                            mView.isHaveNotice((NewNoticeBean) httpData.getData());

                        }
                    }
                });
    }


    public void getUserInfo() {
        httpService.userInfo("pb")
                .tag(this)
                .execute(new JsonCallBack<HttpData<UserBean>>(this) {
                    @Override
                    public void onSuccess(Response<HttpData<UserBean>> response) {
                        HttpData httpData = response.body();
                        if (httpData.getStatus() == HttpConfig.OK) {
                            UserBean userBean = (UserBean) httpData.getData();
                            mView.updateUser(userBean);
                        }
                    }
                });
    }

    /**
     * 版本升级
     */
    public void updata(String version, boolean tip) {
        httpService.updata(version)
                .tag(this)
                .execute(new JsonCallBack<HttpData<UpdataBean>>(this) {
                    @Override
                    public void onSuccess(Response<HttpData<UpdataBean>> response) {
                        HttpData httpData = response.body();
                        if (tip) {
                            ToastUtil.showShort(httpData.msg);
                        }
                        if (httpData.getStatus() == HttpConfig.OK) {
                            mView.checkUpdata((UpdataBean) httpData.getData());
                        }
                    }
                });
    }

}
